#!/usr/bin/perl
use strict;
use warnings;

sub print_file_content {  
  my $filename = $_[0];
  my $fh;
  open( $fh, "<", "$filename" ) or die "Cant open $filename: $!";
  my @daten = <$fh>;
  close($fh);
  print "file $_[1] :\n";
  for my $i ( 0 .. @daten - 1 ) {
    if ($daten[$i] =~ /^Date:/ | $daten[$i] =~ /^Version:/) {
      print "   $daten[$i]";
    }
  }
}

use Fcntl ':flock';

my $filename = "/home/voellenk/stratlab_workdir/R_Pakete/candlesticks/pkg/DESCRIPTION";
print_file_content($filename, "before");

my $fh;
open( $fh, "+<", "$filename" ) or die "Cant open $filename: $!";
flock( $fh, 0 );
my @daten = <$fh>;
my ( $number, $date );
my $changed;
for my $i ( 0 .. @daten - 1 ) {
    if ( $daten[$i] =~ /^Date:\s+\d{4}-\d\d?-\d\d?/ ) {
        my @datum = ( localtime(time) )[ 3 .. 5 ];
        $daten[$i] = sprintf(
            "Date: %4d-%02d-%02d\n",
            $datum[2] + 1900,
            $datum[1] + 1,
            $datum[0]
        );
        $changed++;
    }
    elsif ( $daten[$i] =~ /^Version:\s+\d+\.\d+\-\d+$/ ) {
        $daten[$i] =~ s/^(Version:\s+\d+\.\d+\-)(\d+)$/"$1".(1+$2)/e;
        $changed++;
    }
}
if ($changed) {
  seek( $fh, 0, 0 ) or die "Can't rewind $filename: $!\n";
  truncate( $fh, 0 );
  print $fh @daten;
}
close($fh) or die "Cant close $filename: $!";

print_file_content($filename, "after");
__END__
